//
//  MNDDetaiRootViewController.m
//  minidai
//
//  Created by 谭谭伟 on 2017/5/31.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDDetaiRootViewController.h"
#import "MNDFinaceDetailModel.h"
#import "MNDManageDetailViewController.h"
#import "UIImage+JKColor.h"
#import "SYRefreshControl.h"
#import "MNDLoginUserModel.h"
#import "MNDRiskAssessWebViewController.h"

typedef NS_ENUM(NSInteger, ScrollType) {
    ScrollTypeDown = 0,
    ScrollTypeUp   = 1
};
@interface MNDDetaiRootViewController ()

@property (nonatomic, strong) MNDFinaceDetailModel *detaiModel;

@property (strong, nonatomic) UIImage *naviBarImage;

@property (weak, nonatomic) IBOutlet UIView *headerView;

@end

@implementation MNDDetaiRootViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.tableView.scrollEnabled = NO;
    NSDictionary *dict = @{ @"brrowCode":self.brrowCode};
    [[NSNotificationCenter defaultCenter] postNotificationName:@"senderBorrowCode" object:dict];
//    self.navigationController.navigationBar.backgroundColor = [UIColor redColor];
    [self setupUI];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(scrollCell:) name:@"scroll_up_or_down" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showRiskAlert:) name:@"show_risk_assessment_notification" object:nil];
    
    if (kScreenHeight >= 812) {
        self.headerView.frame = CGRectMake(0, 0, kScreenWidth, 88);
    }
    [self initBackButtonItem];
}

- (void)initBackButtonItem {
    
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    
    UIImage *itemImage = [UIImage imageNamed:@"navi_back_btn_black"];
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithImage: itemImage
                                                             style: UIBarButtonItemStylePlain
                                                            target: self
                                                            action: @selector(backAction:)];
    
    
    [item setTintColor:kColorBlack];
    if (@available(iOS 11.0, *)) {
        self.navigationItem.leftBarButtonItem = item;
    } else {
        self.navigationItem.leftBarButtonItems = @[spaceItem, item];
    }
}

#pragma mark - Action

- (void)backAction:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    if (!self.naviBarImage) {
        self.naviBarImage = [UIImage new];
    }
//    [self loadData];
    [self.navigationController.navigationBar setBackgroundImage: self.naviBarImage forBarMetrics:UIBarMetricsDefault];
    self.navigationController.navigationBar.shadowImage = [UIImage new];
    
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor whiteColor]}];
    for (UIBarButtonItem *item in self.navigationItem.leftBarButtonItems) {
        [item setTintColor:[UIColor whiteColor]];
    }
    
    if ([MNDLoginUserModel isUserLogin]) {
        [self loadUserInfos];
        
        
    }
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController.navigationBar setBackgroundImage:[UIImage jk_imageWithColor:[UIColor whiteColor]] forBarMetrics:UIBarMetricsDefault];
    
    UIImage *image = [UIImage jk_imageWithColor:[UIColor colorWithRed:239/255.0 green:239/255.0 blue:244/255.0 alpha:0.3]];
    self.navigationController.navigationBar.shadowImage = image;
    [self.navigationController.navigationBar setTitleTextAttributes:@{NSForegroundColorAttributeName: [UIColor blackColor]}];
}

#pragma mark -加载数据

- (void)loadUserInfos {
    
    WeakSelf(self);
    [APIManager sendRequestWithPath:API_USER_BASE_INFO
                         parameters:[MNDSign signedParam]
                             method:kXMHTTPMethodGET
                          onSuccess:^(ResponseModel *responseModel) {
                              
                              if (responseModel.status == ResponseSuccess) {
                                  [NetworkProgressHUD hideHud];
                                  weakself.userModel = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
                                  NSLog(@"data: %@", responseModel.data);
                              } else {
                                  NSDictionary *dict = responseModel.msg;
                                  if (dict && dict.count > 0) {
                                      [NetworkProgressHUD showHudMsg:dict[@"error"]];
                                  } else {
                                      [NetworkProgressHUD showHudMsg:@"获取数据失败"];
                                  }
                              }
                              
                          } onFailure:^(NSError *error) {
                              [NetworkProgressHUD showHudNetworkError:error];
                          }];
}

- (void)showRiskAlert:(NSNotification *)motification {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"您还没有完成[出借用户风险等级测评]，根据金融监管政策要求，用户需要先完成评估才能出借。" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *action = [UIAlertAction actionWithTitle:@"去测评" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
        
        MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
        riskVC.webViewUrl = self.userModel.evaluationUrl;
        riskVC.indexOfViewController = index;
        riskVC.title = @"风险测评";
        [self.navigationController pushViewController:riskVC animated:YES];
    }];
    [alert addAction:cancelAction];
    [alert addAction:action];
    
    [self presentViewController:alert animated:YES completion:^{
        
    }];
}

- (void)setupUI {
    //刷新数据
//    [SYRefreshControl configNormalMJRefresh:self.tableView refreshType:MJRefreshSupportRefresh beginRefresh:NO timeLabelHidden:YES stateLabelHidden:NO refreshBlock:^{
//        [self loadData];
//    } loadMoreBlock:nil];
}
//- (void)configContents {

//    [[NSNotificationCenter defaultCenter] postNotificationName:@"senderDetailModel" object:dict];
//}

- (void)scrollCell:(NSNotification *)notification {
    
    NSInteger scrollType = [notification.object integerValue];
    
    if (scrollType == 0) {
        [self.tableView scrollRectToVisible:CGRectMake(0, 0, kScreenWidth, kScreenHeight) animated:YES];
        self.naviBarImage = [UIImage new];
        [self.navigationController.navigationBar setBackgroundImage:self.naviBarImage forBarMetrics:UIBarMetricsDefault];
    } else {

        self.naviBarImage =  [UIImage jk_imageWithColor:[UIColor colorWithRed:236/255.0 green:107/255.0 blue:76/255.0 alpha:1.0]];
        [self.navigationController.navigationBar setBackgroundImage:self.naviBarImage forBarMetrics:UIBarMetricsDefault];
        [self.tableView scrollRectToVisible:CGRectMake(0, kScreenHeight, kScreenWidth, kScreenHeight) animated:YES];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return 2;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat screenHeight = [UIScreen mainScreen].bounds.size.height;

    if (kScreenHeight >= 812) {
        //要减掉导航条的高度
        return screenHeight - 88;
    } else {
        //要减掉导航条的高度
        return screenHeight - 64;
    }
}



@end
